package com.baobao.service;

import com.baobao.dao.ChatDAO;
import com.baobao.domain.Chat;

import java.util.Calendar;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Spring service that handles CRUD requests for Chat entities
 * 
 */

@Service("ChatService")
@Transactional
public class ChatServiceImpl implements ChatService {

	/**
	 * DAO injected by Spring that manages Chat entities
	 * 
	 */
	@Autowired
	private ChatDAO chatDAO;

	/**
	 * Instantiates a new ChatServiceImpl.
	 *
	 */
	public ChatServiceImpl() {
	}

	/**
	 * Return all Chat entity
	 * 
	 */
	@Transactional
	public List<Chat> findAllChats(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Chat>(chatDAO.findAllChats(startResult, maxRows));
	}

	/**
	 * Load an existing Chat entity
	 * 
	 */
	@Transactional
	public Set<Chat> loadChats() {
		return chatDAO.findAllChats();
	}

	/**
	 */
	@Transactional
	public Chat findChatByPrimaryKey(String sender, String receiver, Calendar date) {
		return chatDAO.findChatByPrimaryKey(sender, receiver, date);
	}
	
	@Transactional
	public Set<Chat> findChatByMaxDateAndPhone(String sender, String receiver){
		return chatDAO.findChatByMaxDateAndPhone(sender, receiver);
	}
	
	@Transactional
	public Set<Chat> findChatByPhoneAndStatus(String sender, String receiver, String status){
		return chatDAO.findChatByPhoneAndStatus(sender, receiver, status);
	}
	
	@Transactional
	public Set<Chat> findChatByReceiverAndLatestMsgnum(String receiver,Calendar startDate,Integer msgnum){
		return chatDAO.findChatByReceiverAndLatestMsgnum(receiver,startDate,msgnum);
	}

	/**
	 * Save an existing Chat entity
	 * 
	 */
	@Transactional
	public void saveChat(Chat chat) {
		Chat existingChat = chatDAO.findChatByPrimaryKey(chat.getSender(), chat.getReceiver(), chat.getDate());

		if (existingChat != null) {
			if (existingChat != chat) {
				existingChat.setSender(chat.getSender());
				existingChat.setReceiver(chat.getReceiver());
				existingChat.setDate(chat.getDate());
				existingChat.setStatus(chat.getStatus());
				existingChat.setText(chat.getText());
				existingChat.setUniqueId(chat.getUniqueId());
			}
			chat = chatDAO.store(existingChat);
		} else {
			chat = chatDAO.store(chat);
		}
		chatDAO.flush();
	}

	/**
	 * Delete an existing Chat entity
	 * 
	 */
	@Transactional
	public void deleteChat(Chat chat) {
		chatDAO.remove(chat);
		chatDAO.flush();
	}

	/**
	 * Return a count of all Chat entity
	 * 
	 */
	@Transactional
	public Integer countChats() {
		return ((Long) chatDAO.createQuerySingleResult("select count(*) from Chat o").getSingleResult()).intValue();
	}
}
